package com.wu.util;

import cn.hutool.core.collection.CollectionUtil;
import lombok.Data;
import lombok.ToString;

import java.util.Collections;
import java.util.List;

@Data
@ToString
public class PageUtil {

    private int pageNum = 1; // 页码
    private int pageSize = 10; // 分页单位
    private int startNum; // 启始条数
    private int endNum; // 结束条数
    private int from;
    private int esSize;
    private String esResult;
    private String esType;

    public static PageUtil getPageUtil(int pageNum, int pageSize) {
        PageUtil pageUtil = new PageUtil();
        pageUtil.pageNum = pageNum < 1 ? pageUtil.pageNum : pageNum;
        pageUtil.pageSize = pageSize;
        pageUtil.startNum = (pageUtil.pageNum - 1) * pageUtil.pageSize;
        pageUtil.endNum = pageUtil.pageNum * pageUtil.pageSize - 1;
        return pageUtil;
    }

    /****
     * 根据分页信息返回需要页的集合数据
     * @param <T>
     * @param list 需要分页的集合
     * @param pageSize
     * @param currentPage
     * @return
     */
    public static <T> List<T> paginate(List<T> list, int pageSize, int currentPage) {
        if (CollectionUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        int totalPage = (int)Math.ceil((double)list.size() / pageSize);
        // 如果当前页大于总页数，返回空数组
        if (currentPage > totalPage) {
            return Collections.emptyList();
        }
        int startIndex = (currentPage-1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, list.size());
        return list.subList(startIndex, endIndex);
    }
}
